{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "find faces by OpenCV.\n",
    "\"\"\"\n",
    "import cv2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "下列代码依赖于训练好的resnet10模型，当让你可以对下面代码稍作改造使用传统的方法来检测人脸。\n",
    "\"\"\"\n",
    "model_file  = \"res10_300x300_ssd_iter_140000_fp16.caffemodel\"\n",
    "config_file = \"deploy.prototxt\"\n",
    "net         = cv2.dnn.readNetFromCaffe(config_file, model_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(121, 121, 3)\n"
     ]
    }
   ],
   "source": [
    "threshold = 0.9\n",
    "img = cv2.imread('lena.jpg')\n",
    "\n",
    "print(img.shape)\n",
    "frameHeight = img.shape[0]\n",
    "frameWidth  = img.shape[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300),\n",
    "                             [104, 117, 123], False, False)\n",
    "net.setInput(blob)\n",
    "detections = net.forward()\n",
    "\n",
    "bboxes = []\n",
    "for i in range(detections.shape[2]):\n",
    "    detection_score = detections[0, 0, i, 2]\n",
    "    if detection_score > threshold:\n",
    "        x1 = int(detections[0, 0, i, 3] * frameWidth)\n",
    "        y1 = int(detections[0, 0, i, 4] * frameHeight)\n",
    "        x2 = int(detections[0, 0, i, 5] * frameWidth)\n",
    "        y2 = int(detections[0, 0, i, 6] * frameHeight)\n",
    "        cv2.rectangle(img, (x1,y1), (x2,y2), (255,0,0),2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cv2.imwrite('found_face.jpg', img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
